package net;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * HttpClient 简易
 * (客户端的 HTTP编程)
 */
public class HttpClient {
    private static Logger log = Logger.getLogger(HttpClient.class.getSimpleName());

    public static void main(String[] args) throws IOException {
//        HttpGet();
        HttpPost();
    }

    public static void HttpGet() throws IOException {

        // 早期 JDK 范围 HTTP
        URL url = new URL("http://httpbin.org/get");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setUseCaches(false);
        // 设置 HTTP 头  (Request Header)
        connection.setRequestProperty("Accept", "*/*");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36");
        // 连接并发送 HTTP请求
        connection.connect();
        // 判断 HTTP 响应
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new RuntimeException("Bad Response");
        }
        System.out.println(connection.getResponseMessage());
        Map<String, List<String>> map = connection.getHeaderFields();
        for (String key : map.keySet()) {
            System.out.println(key + " : " + map.get(key));
        }

        // 需要手动处理 `InputStream`, 所以用起来很麻烦, jdk 11 引入 `HttClient`
        try (InputStream inputStream = connection.getInputStream()){

        }

        // 断开连接
        connection.disconnect();
    }

    public static void HttpPost() throws IOException {
        URL url = new URL("http://httpbin.org/post");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");
        // 发送数据
        connection.setDoOutput(true);

        byte[] postData = "loginName=tt&pass=121".getBytes("UTF-8");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Content-Length", String.valueOf(postData.length));

        connection.connect();

        System.out.println(connection.getResponseCode());
        System.out.println(connection.getResponseMessage());

        ByteArrayOutputStream responseBuffer = new ByteArrayOutputStream();

        try (InputStream input = connection.getInputStream()){
            byte[] buffer = new byte[1024];
            for (; ; ) {
                int n = input.read(buffer);
                if (n == -1) {
                    break;

                }
                responseBuffer.write(buffer, 0, n);
            }
            System.out.println( responseBuffer.toString());

        } finally {
            connection.disconnect();
        }

    }
}
